// pages/export/expert.js
const app = getApp();
var util = require("../../utils/util.js");

const APP_ID ='wxac721997e649a1d0';//输入小程序appid  
const APP_SECRET ='';//输入小程序app_secret  
var OPEN_ID=''//储存获取到openid  
var SESSION_KEY=''//储存获取到session_key  

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSee:0, //1 能看 0不可以看
    plandescription:"",
    userInfo: {},
    list1List: [],
    lotterytype:'',
    timeType:'',
    days:'',
    house:'',
    minute:'',
    second:'',
    tr0:'',
    tr1:'',
    tr2:'',
    tr3:'',
    attentionState:'',
    cauthorid:'',
    planNo:'',
  },
  getuserInfo(planNos) {
    let url = app.globalData.url.detail;
    let self = this
    let userIds =  app.globalData.userId;
    let planNo = planNos?planNos:self.data.planNo
    wx.request({
      url: url,
      data: {
        'planNo': planNo,
        'cfrom': app.globalData.cfrom,
        "userId":userIds
      },
      method: "GET",
      success(res) {
        let code = res.statusCode
        if (code == '200') {
          let data = res.data
          if (data.status == '_0000') {
            let datas = data.data
            let userInfo = {
              'imgUrl': datas.authheadImlUrl,
              'name': datas.authName,
              'authTag': datas.authTag,
              'mess': datas.authdescription,
              'plantitle':datas.plantitle,
              'plansummary':datas.plansummary,
              'salepeice':datas.salepeice,
              'fannums':datas.fansum
            }
            self.setData({
              isSee:datas.isSee,
              plandescription:datas.plandescription,
              userInfo: userInfo,
              lotterytype:datas.lotterytype,
              list1List:datas.planforecastitems,
              timeType:datas.timeType,
              attentionState:datas.fans,
              cauthorid:datas.authorid,
              planNo:planNo,
            })
            self.leftTimer(datas.begintime)
            if (datas.lotterytype == 3 || datas.lotterytype == 4) {
              self.listTemp(datas.planforecastitems)
            }
          }
        } else {
          console.log(res.errMsg)
        }
      },
      fail(res) {
        console.log(res.statusCode)
      }
    })
  },
  listTemp(data){
    var self = this
    var homes = [], items = [], guests = [], ths = [];
    data.forEach(function (val,i) {
      homes.push(val.homeTeam);
      guests.push(val.guestTeam);
      items.push(tdHtml(val.items));
      ths.push(i < 9 ? '0' + (i + 1) : i + 1);
    });
    function tdHtml(item) {
      if (!item) { item = '-';};
      item = item.replace(/3/, '胜');
      item = item.replace(/1/, '平');
      item = item.replace(/0/, '负');
      item = item.replace(/,/g, '');
      return item
    };
    self.setData({
      tr0:ths,
      tr1:homes,
      tr2:items,
      tr3:guests,
    })
  },
  leftTimer(time){ //倒计时
    var self = this
    var gsTime = time.toString().split(' ');
    var gsTimeD = gsTime[0].split('-');
    gsTime =gsTimeD[0]+'/'+ gsTimeD[1]+'/'+gsTimeD[2]+' '+gsTime[1];
    var timer = null ;
    timer = setInterval(function(){
      var intDiff =(new Date(gsTime).getTime() - new Date().getTime()) / 1000;        
      var day=0,
        hour=0,
        minute=0,
        second=0;//时间默认值    
      if(intDiff > 0){
        day = Math.floor(intDiff / (60 * 60 * 24));
        hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
        minute = Math.floor(intDiff / 60) - (day * 24 * 60) - (hour * 60);
        second = Math.floor(intDiff) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
        if (day > 0) { 
          day = day + '天'
        }else{
          day = ''
        }
        if (hour <= 9) hour = '0' + hour;
        if (minute <= 9) minute = '0' + minute;
        if (second <= 9) second = '0' + second;
        self.setData({
          days:day,
          house:hour,
          minute:minute,
          second:second
        })
       intDiff--;
      }else{
        clearTimeout(timer)
      }
    }, 1000);
  },
  handleAttention(){
    var self = this
    let url = app.globalData.url.interestManage;
    let userIds =  app.globalData.userId;
    let planNos = self.data.planNo
    let cauthorid = self.data.cauthorid
    let attentionState = self.data.attentionState

    var type='',toast;
    if (!userIds) {
        wx.navigateTo({url:'../loginPhone/index'})
    }else{
     if (attentionState == 0) {
        type = 1
        toast = '关注成功'
      }else{
        type = 0
        toast = '取消成功'
      }
      wx.request({
        url: url,
        data:{
          author:cauthorid,
          type:type, //0取消关注 1关注
          userId:userIds
        },
        method: "GET",
        success(res) {
          let code = res.statusCode
          if (code == '200') {
            let data = res.data
            if (data.status == '_0000') {
                  wx.showToast({
                      title:toast,
                      icon:'success'
                  });
                  self.getuserInfo(planNos)
              }
          } else {
            console.log(res.errMsg)
          }
        },
        fail(res) {
          console.log(res.statusCode)
        }
      })
    }
  },
  wxPay (e) {
    let self = this
    var total_fee = e.currentTarget.dataset.money
    let payUrl = app.globalData.url.wxpay
    let cfrom = app.globalData.cfrom
    let phone = app.globalData.userPhone
    let userIds = app.globalData.userId
    let password = app.globalData.userPass
    let versions = app.globalData.version
    var openIds = wx.getStorageSync('openId')
    if (!userIds) {
        wx.navigateTo({url:'../loginPhone/index'})
    }else{
      wx.request({
        url: payUrl,
        method: "get",
        data: {
          channel:cfrom,
          version:versions,
          cfrom:cfrom,
          phone:phone,
          userId:userIds,
          password:password,
          desc:'微信',
          money:total_fee,
          payWay:'10_wxpay',
          openId:openIds
        },
        header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) { //后端返回的数据
          var data = res.data.data;
          var payInfos = data["payInfos"]
          var packages = 'prepay_id='+ payInfos['prepayid'];
          let isRefund = data.isRefund || 0;
          wx.requestPayment({
            timeStamp: payInfos['timestamp'],
            nonceStr: payInfos['noncestr'],
            package: packages,
            signType: 'MD5',
            paySign: payInfos['sign'],
            success: function (res) {
              self.buyExplain(isRefund)
            },
            fail: function (res) {
              console.log(res);
            }
          })
          
        }
      });
    }
  },
  buyExplain(isRefundFromUrl){
    let self =this
    let url = app.globalData.url.buyExplain
    let cfrom = app.globalData.cfrom
    let planNos = self.data.planNo
    let versions = app.globalData.version
    let phone = app.globalData.userPhone
    let userIds = app.globalData.userId
    let password = app.globalData.userPass
    wx.request({
        url: url,
        method: "get",
        data: {
          'planNo':planNos,
          'cfrom':cfrom,
          'version':versions,
          'channel': cfrom,
          'isRefund': isRefundFromUrl,
          'buyType': 1,
          'phone':phone,
          'userId':userIds,
          'password':password
        },
        header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) { //后端返回的数据
          if(res.data.status == "_0000"){
           self.getuserInfo()
          }
        }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let planNo = options.planNo
    this.getuserInfo(planNo);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})